<template>
  <div class="disaster-analysis-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="analysis-card">
          <template #header>
            <div class="card-header">
              <span>灾情统计分析</span>
              <div class="water-drop"></div>
            </div>
          </template>

          <div class="filter-section">
            <el-select v-model="timeRange" placeholder="选择时间范围" @change="loadDisasterData">
              <el-option label="最近7天" value="7days" />
              <el-option label="最近30天" value="30days" />
              <el-option label="最近90天" value="90days" />
              <el-option label="全部" value="all" />
            </el-select>

            <el-select v-model="disasterType" placeholder="灾害类型" @change="loadDisasterData">
              <el-option label="全部类型" value="" />
              <el-option label="地震" value="地震" />
              <el-option label="洪水" value="洪水" />
              <el-option label="台风" value="台风" />
              <el-option label="滑坡" value="滑坡" />
              <el-option label="泥石流" value="泥石流" />
              <el-option label="火灾" value="火灾" />
              <el-option label="其他" value="其他" />
            </el-select>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>受灾人员统计</span>
            </div>
          </template>
          <div class="chart-container" id="peopleChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>经济损失与受灾面积</span>
            </div>
          </template>
          <div class="chart-container" id="economicChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>灾害类型分布</span>
            </div>
          </template>
          <div class="chart-container" id="typeChart"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>救援资源统计</span>
            </div>
          </template>
          <div class="chart-container" id="rescueChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="data-card">
          <template #header>
            <div class="card-header">
              <span>灾情数据明细</span>
            </div>
          </template>
          <el-table :data="disasterList" style="width: 100%" border stripe v-loading="loading">
            <el-table-column prop="attributes.Name" label="名称" min-width="120" />
            <el-table-column prop="attributes.DisasterType" label="类型" width="100" />
            <el-table-column label="受灾人数" width="100">
              <template #default="scope">
                {{ getDisasterImpactData(scope.row, 'affectedPeople') }} 人
              </template>
            </el-table-column>
            <el-table-column label="受伤人数" width="100">
              <template #default="scope">
                {{ getDisasterImpactData(scope.row, 'injuredPeople') }} 人
              </template>
            </el-table-column>
            <el-table-column label="死亡人数" width="100">
              <template #default="scope">
                {{ getDisasterImpactData(scope.row, 'deathCount') }} 人
              </template>
            </el-table-column>
            <el-table-column label="经济损失" width="120">
              <template #default="scope">
                {{ getDisasterImpactData(scope.row, 'economicLoss') }} 万元
              </template>
            </el-table-column>
            <el-table-column label="受灾面积" width="120">
              <template #default="scope">
                {{ getDisasterImpactData(scope.row, 'affectedArea') }} km²
              </template>
            </el-table-column>
            <el-table-column label="确认时间" min-width="160">
              <template #default="scope">
                {{ getConfirmTime(scope.row) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'

// 状态变量
const loading = ref(false)
const disasterList = ref<any[]>([])
const timeRange = ref('30days')
const disasterType = ref('')

// 图表实例
let peopleChart: echarts.ECharts | null = null
let economicChart: echarts.ECharts | null = null
let typeChart: echarts.ECharts | null = null
let rescueChart: echarts.ECharts | null = null

// 灾情图层
let disasterLayer: FeatureLayer | null = null

onMounted(() => {
  initCharts()
  initDisasterLayer()
  loadDisasterData()

  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 销毁图表实例
  peopleChart?.dispose()
  economicChart?.dispose()
  typeChart?.dispose()
  rescueChart?.dispose()

  // 移除事件监听
  window.removeEventListener('resize', handleResize)
})

// 初始化图表
const initCharts = () => {
  // 初始化各个图表
  peopleChart = echarts.init(document.getElementById('peopleChart'))
  economicChart = echarts.init(document.getElementById('economicChart'))
  typeChart = echarts.init(document.getElementById('typeChart'))
  rescueChart = echarts.init(document.getElementById('rescueChart'))
}

// 初始化灾情图层
const initDisasterLayer = () => {
  disasterLayer = new FeatureLayer({
    url: 'https://services7.arcgis.com/chXsWZj8U6NqFZb6/arcgis/rest/services/DisasterDetectionAndRescueSystem/FeatureServer/0',
    outFields: ['*'],
  })
}

// 加载灾情数据
const loadDisasterData = async () => {
  if (!disasterLayer) return

  loading.value = true
  try {
    // 构建查询参数
    const query = disasterLayer.createQuery()
    query.outFields = ['*']
    query.returnGeometry = true

    // 构建时间范围查询条件
    let whereClause = '1=1'

    if (timeRange.value !== 'all') {
      const now = new Date()
      let pastDate = new Date()

      switch (timeRange.value) {
        case '7days':
          pastDate.setDate(now.getDate() - 7)
          break
        case '30days':
          pastDate.setDate(now.getDate() - 30)
          break
        case '90days':
          pastDate.setDate(now.getDate() - 90)
          break
      }

      // 假设有一个CreationDate字段，实际使用时需要根据实际字段调整
      // whereClause = `CreationDate >= '${pastDate.toISOString()}' AND CreationDate <= '${now.toISOString()}'`
    }

    // 添加灾害类型过滤
    if (disasterType.value) {
      whereClause += ` AND DisasterType = '${disasterType.value}'`
    }

    query.where = whereClause

    // 执行查询
    const results = await disasterLayer.queryFeatures(query)

    // 更新列表数据
    disasterList.value = results.features.map((feature) => {
      // 在存储前对结果数据进行序列化处理，移除不可序列化的属性
      const safeFeature = JSON.parse(
        JSON.stringify(feature, (key, value) => {
          // 过滤掉ArcGIS特殊属性或不可序列化的对象
          if (key === '__accessor__' || typeof value === 'function' || key.startsWith('_')) {
            return undefined
          }
          return value
        }),
      )
      return safeFeature
    })

    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('加载灾情数据失败:', error)
    ElMessage.error('加载灾情数据失败')
  } finally {
    loading.value = false
  }
}

// 更新所有图表
const updateCharts = () => {
  updatePeopleChart()
  updateEconomicChart()
  updateTypeChart()
  updateRescueChart()
}

// 更新受灾人员统计图表
const updatePeopleChart = () => {
  if (!peopleChart) return

  // 计算总数
  let totalInjured = 0
  let totalDeath = 0

  disasterList.value.forEach((disaster) => {
    totalInjured += parseInt(getDisasterImpactData(disaster, 'injuredPeople')) || 0
    totalDeath += parseInt(getDisasterImpactData(disaster, 'deathCount')) || 0
  })

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: ['受伤人数', '死亡人数'],
    },
    series: [
      {
        name: '人员伤亡统计',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2,
        },
        label: {
          show: false,
          position: 'center',
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold',
          },
        },
        labelLine: {
          show: false,
        },
        data: [
          { value: totalInjured, name: '受伤人数' },
          { value: totalDeath, name: '死亡人数' },
        ],
      },
    ],
  }

  peopleChart.setOption(option)
}

// 更新经济损失与受灾面积图表
const updateEconomicChart = () => {
  if (!economicChart) return

  // 提取数据
  const disasterNames = disasterList.value.map((disaster) => disaster.attributes.Name)
  const economicLosses = disasterList.value.map(
    (disaster) => parseFloat(getDisasterImpactData(disaster, 'economicLoss')) || 0,
  )
  const affectedAreas = disasterList.value.map(
    (disaster) => parseFloat(getDisasterImpactData(disaster, 'affectedArea')) || 0,
  )

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    legend: {
      data: ['经济损失(万元)', '受灾面积(km²)'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: [
      {
        type: 'category',
        data: disasterNames,
        axisLabel: {
          rotate: 45,
          interval: 0,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '经济损失(万元)',
        position: 'left',
      },
      {
        type: 'value',
        name: '受灾面积(km²)',
        position: 'right',
      },
    ],
    series: [
      {
        name: '经济损失(万元)',
        type: 'bar',
        yAxisIndex: 0,
        data: economicLosses,
      },
      {
        name: '受灾面积(km²)',
        type: 'line',
        yAxisIndex: 1,
        data: affectedAreas,
      },
    ],
  }

  economicChart.setOption(option)
}

// 更新灾害类型分布图表
const updateTypeChart = () => {
  if (!typeChart) return

  // 统计各类型灾害数量
  const typeCount: Record<string, number> = {}

  disasterList.value.forEach((disaster) => {
    const type = disaster.attributes.DisasterType || '未知'
    typeCount[type] = (typeCount[type] || 0) + 1
  })

  const data = Object.entries(typeCount).map(([name, value]) => ({ name, value }))

  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)',
    },
    legend: {
      type: 'scroll',
      orient: 'vertical',
      right: 10,
      top: 20,
      bottom: 20,
    },
    series: [
      {
        name: '灾害类型',
        type: 'pie',
        radius: '55%',
        center: ['40%', '50%'],
        data: data,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  }

  typeChart.setOption(option)
}

// 更新救援资源统计图表
const updateRescueChart = () => {
  if (!rescueChart) return

  // 提取数据
  const disasterNames = disasterList.value.map((disaster) => disaster.attributes.Name)
  const rescueTeams = disasterList.value.map(
    (disaster) => parseInt(getDisasterImpactData(disaster, 'rescueTeams')) || 0,
  )
  const rescuePersonnel = disasterList.value.map(
    (disaster) => parseInt(getDisasterImpactData(disaster, 'rescuePersonnel')) || 0,
  )

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999',
        },
      },
    },
    legend: {
      data: ['救援队伍数量', '救援人员数量'],
    },
    xAxis: [
      {
        type: 'category',
        data: disasterNames,
        axisPointer: {
          type: 'shadow',
        },
        axisLabel: {
          rotate: 45,
          interval: 0,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        name: '救援队伍数量',
        min: 0,
        interval: 5,
      },
      {
        type: 'value',
        name: '救援人员数量',
        min: 0,
        interval: 50,
      },
    ],
    series: [
      {
        name: '救援队伍数量',
        type: 'bar',
        data: rescueTeams,
      },
      {
        name: '救援人员数量',
        type: 'line',
        yAxisIndex: 1,
        data: rescuePersonnel,
      },
    ],
  }

  rescueChart.setOption(option)
}

// 处理窗口大小变化
const handleResize = () => {
  peopleChart?.resize()
  economicChart?.resize()
  typeChart?.resize()
  rescueChart?.resize()
}

// 获取受灾情况数据
const getDisasterImpactData = (disaster: any, field: string) => {
  if (!disaster) return '0'

  try {
    const messageJson = disaster.attributes.DisasterMessageJson
    if (!messageJson) return '0'

    const messageData = JSON.parse(messageJson)
    if (!messageData.disasterImpact) return '0'

    return messageData.disasterImpact[field] || '0'
  } catch (e) {
    return '0'
  }
}

// 获取确认时间
const getConfirmTime = (disaster: any) => {
  if (!disaster) return ''

  try {
    const messageJson = disaster.attributes.DisasterMessageJson
    if (!messageJson) return ''

    const messageData = JSON.parse(messageJson)
    if (!messageData.confirmTime) return ''

    return new Date(messageData.confirmTime).toLocaleString()
  } catch (e) {
    return ''
  }
}
</script>

<style scoped>
.disaster-analysis-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.analysis-card,
.chart-card,
.data-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  color: #2c3e50;
  font-weight: bold;
  font-size: 18px;
  padding-bottom: 8px;
  border-bottom: 2px solid #eaeaea;
}

.water-drop {
  position: absolute;
  top: -10px;
  right: -10px;
  width: 30px;
  height: 30px;
  background-color: rgba(64, 158, 255, 0.2);
  border-radius: 50%;
  z-index: -1;
}

.filter-section {
  display: flex;
  gap: 20px;
  margin: 15px 0;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
  width: 100%;
}

@media (max-width: 768px) {
  .chart-container {
    height: 300px;
  }
}
</style>
